#!/bin/bash

# Create the array for printer names and loop through them

printer_names=( baskerville cleveland lib_iif lib_1st_flr lib_2nd_flr norris2 read2 inslab2 \
		scilab scilib jrc_email younker2 helpdesk2 duerer gencomp2 rose ccl3_bw )

for ((i=0; i < ${#printer_names[@]}; i++))
do

# Sets the printer name to the element of the array, but capitalized

printer=`echo "${printer_names[$i]}" | tr "[:lower:]" "[:upper:]"`

###############################################################################################
#											       #
# Here, we check 4 different things, then send an out-of-order e-mail accordingly...           #
#											       #
#  1.) Check to see if the toner level file is empty. If it is, that's an indication           #
#      that 'toner.sh' couldn't download the status page, and the printer may be out-of-order  #
#  2.) Check to see if the printer responds to pings					       #
#  3.) Check the oo_email file. The status of this is based on whether or not a TC has set     #
#      out-of-order e-mails to be on or not						       #
#  4.) Finally, check the open_status file to see if the lab is open			       #
#											       #
# If all of these criteria are met, send an out-of-order e-mail. Otherwise, check to see       #
# if the toner level is less than or equal to 1%, and send a low-toner e-mail, or do nothing   #
#											       #
###############################################################################################

[[ -s $HOME/printers/toner_level/"${printer_names[$i]}"_level ]]

if [ `echo $?` == 1 ]
then
	ping "${printer_names[$i]}".grinnell.edu -c 4
	if [ `echo $?` == 1 ]
	then
		email_status=`cat $HOME/printers/oo_status/oo_emails/"${printer_names[$i]}"_email`
		if [ $email_status == 1 ]
		then
			open_status=`cat $HOME/printers/open_statuses/"${printer_names[$i]}"`
			if [ $open_status == 1 ]
			then
				echo "You should check the status page at http://"${printer_names[$i]}".grinnell.edu, or see if the printer responds to pings. Note that the printer may simply be turned off." | mail -s "$printer may be out-of-order" helpdesk@grinnell.edu -c satherdy@grinnell.edu,botmille@grinnell.edu -a "Reply-To: satherdy@grinnell.edu"
			fi
		fi
	fi
else
	toner_level=`tail $HOME/printers/toner_level/"${printer_names[$i]}"_level | egrep "[0-9]{1,}" -o`
	if [ $toner_level -le 1 ]
	then
		echo "... and should be replaced soon" | mail -s "The toner in $printer is getting low" helpdesk@grinnell.edu -c satherdy@grinnell.edu,botmille@grinnell.edu -a "Reply-To: satherdy@grinnell.edu"
	fi
fi
done

exit 0
